package com.maimao.mg.service;

import com.maimao.core.utils.DateUtils;
import com.maimao.model.info.Coupon;
import com.maimao.model.info.MgCoupon;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author MaoLin Wang
 * @date 2021/1/7 11:49 下午
 */
@Service
public class MgCouponService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询当前店铺下的所有店铺优惠券和包含goodsId的商品优惠券
     *
     * @return
     */
    public List<MgCoupon> selectGoodsCoupon(Long shopId, Long goodsId) {
        Query query = new Query();
        query.addCriteria(
                Criteria.where("shopId").is(shopId)
                .and("deleted").is(0)
                .and("endTime").gte(DateUtils.now())
                .orOperator(
                        Criteria.where("where").in(1, 2)
                                .and("goodsId").in(String.valueOf(goodsId)),
                        Criteria.where("shopId").is(shopId)
                                .and("where").is(3)
                )
        );
        query.fields()
                .include("_id")
                .include("name")
                .include("discountPrice")
                .include("endTime")
                .include("count")
                .include("takeCount");
        List<MgCoupon> mgCoupons = mongoTemplate.find(query, MgCoupon.class);
        return mgCoupons;
    }

    /**
     * 查询当前店铺下的所有优惠券
     */
    public List<MgCoupon> queryByShopId(Long shopId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("shopId").is(shopId).and("endTime").gte(DateUtils.now()).and("startTime").lte(DateUtils.now()));
        return mongoTemplate.find(query, MgCoupon.class);
    }

    /**
     * 使用优惠券添加使用次数
     *
     * @param couponIds
     */

    public int useCoupon(List<Long> couponIds, boolean used) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").in(couponIds));
        Update update = new Update();
        update.inc("used", used ? 1 : -1);
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, MgCoupon.class);
       return (int) updateResult.getMatchedCount();
    }
}
